import axios from 'axios';
import {showFailToast} from 'vant';
import useStore from '@/store/index';
import Router from '@/router/index';
import userInfo from "@/store/modules/userInfo.js";

const baseURL = "http://192.168.110.78:8080";
const request = axios.create({
    timeout: 5000,
    baseURL
});

// 请求拦截器
request.interceptors.request.use(config => {
    const {userInfo} = useStore()
    // 1. 获取用户信息对象
    const token = userInfo.getToken;
    // // 2. 判断是否有token
    if (token) {
        // 3. 设置token
        config.headers.Authorization = `${token}`;
    }
    return config;
}, err => {
    return Promise.reject(err);
});

// 响应拦截器
request.interceptors.response.use(response => {
    // 状态码失败处理
    if (response.data.code !== 200) {
        if (response.data.code == 1011) {
            return handleTokenError(response.data.message)
        }
        showFailToast(response.data.message);
        return Promise.reject(response.data.message);
    }
    return response.data
}, err => {
    // 401 网关失效
    if (err.status === 401) {
        return handleTokenError(err.message)
    }
    return Promise.reject(err);
});

// 请求工具函数
export default (url, method, submitData) => {
    return request({
        url,
        method,
        [method.toLowerCase() === 'get' ? 'params' : 'data']: submitData
    });
};

// token 失效及网关401错误处理
const handleTokenError = (message) => {
    const {userInfo} = useStore()
    showFailToast("登录失效,请重新登录");
    Router.push("/mine")
    userInfo.logout()
    return Promise.reject(message);
}
